import { type Ref, ref, reactive, toRaw, onMounted, h } from "vue";
import editForm from "../form.vue";
import { usePublicHooks } from "@/views/hooks";
import { ElMessageBox } from "element-plus";
import { addDialog } from "@/components/ReDialog";
import { message } from "@/utils/message";
import {
  type AnnouncementDTO,
  getAnnouncementPage,
  createAnnouncement,
  updateAnnouncement,
  deleteAnnouncement,
  getAnnouncementDetail
} from "@/api/announcement";
import {
  getKeyList,
  cloneDeep,
  isAllEmpty,
  deviceDetection
} from "@pureadmin/utils";

export function useNotice(tableRef: Ref) {
  const { switchStyle } = usePublicHooks();
  const form = reactive({
    pageNum: 1,
    pageSize: 10,
    title: "",
    isFeaturedOnHome: ""
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(false);
  const selectedNum = ref(0);
  const switchLoadMap = ref({});
  // 分页配置
  const pagination = reactive({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  // 表格列配置
  const columns: TableColumnList = [
    { label: "公告名称", prop: "title" },
    { label: "公告内容", prop: "content" },
    { label: "发布时间", prop: "publishTime" },
    // { label: "发布人", prop: "CreateUserName" },
    // {
    //   label: "有效",
    //   cellRenderer: scope => (
    //     <el-switch
    //       size={scope.props.size === "small" ? "small" : "default"}
    //       v-model={scope.row.EnabledMark}
    //       active-value={1}
    //       inactive-value={0}
    //       active-text="禁止"
    //       inactive-text="允许"
    //       inline-prompt
    //       style={switchStyle.value}
    //     />
    //   )
    // },
    {
      label: "是否首页滚动",
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.isFeaturedOnHome}
          active-text="是"
          inactive-text="否"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    // { label: "备注", prop: "Description" },
    {
      label: "操作",
      fixed: "right",
      width: "240px",
      slot: "operation" // 包含编辑、删除等操作
    }
  ];
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }
  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    pagination.pageSize = val;
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    pagination.currentPage = val;
    form.pageNum = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    console.log(`handleSelectionChange: ${val}`);
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  function onBatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    if (!curSelected.length) {
      message("请选择要删除的记录", { type: "warning" });
      return;
    }
    const Ids = curSelected.map(item => item.id);
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    deleteDictTypeBatch(Ids).then(() => {
      tableRef.value.getTableRef().clearSelection();
      onSearch();
    });
    message(`已删除用户编号为 ${getKeyList(curSelected, "id")} 的数据`, {
      type: "success"
    });
  }
  // 获取公告列表
  async function onSearch() {
    loading.value = true;
    const { data } = await getAnnouncementPage(toRaw(form));
    dataList.value = data.records;
    pagination.total = data.total;
    pagination.pageSize = data.size;
    pagination.currentPage = data.current;
    setTimeout(() => (loading.value = false), 500);
  }
  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.isFeaturedOnHome ? "首页滚动" : "取消首页滚动"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.title
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        // 编辑
        await updateAnnouncement(row);
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: false
          }
        );
        message("已成功修改", {
          type: "success"
        });
        await onSearch();
      })
      .catch(() => {
        row.status === 0 ? (row.status = 1) : (row.status = 0);
        onSearch();
      });
  }
  // 新增/编辑公告
  function openDialog(type: string, row?: AnnouncementDTO) {
    const title = type === "add" ? "发布" : "编辑";
    addDialog({
      title: `${title}公告信息`,
      props: {
        formInline: {
          id: row?.id || "",
          title: row?.title || "",
          content: row?.content || "",
          // publishTime: row?.publishTime || "",
          isFeaturedOnHome: row?.isFeaturedOnHome || null
        }
      },
      width: "720px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as AnnouncementDTO;
        async function chores() {
          message(`您${title}了公告名称为${curData.title}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          await onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (type === "add") {
              delete curData.id;
              await createAnnouncement(curData);
              await chores();
            } else {
              // 编辑用户
              curData.id = row.id;
              await updateAnnouncement(curData);
              await chores();
            }
          }
        });
      }
    });
  }
  // 删除公告
  function handleDelete(row) {
    // ElMessageBox.confirm(`确认删除公告【${row.title}】?`, "删除确认", {
    //   type: "warning"
    // }).then(() => {
    deleteAnnouncement(row.id).then(() => {
      message(`删除公告 ${row.title} 成功`, { type: "success" });
      // 重置分页到第一页
      pagination.currentPage = 1;
      onSearch();
    });
    // });
  }

  onMounted(async () => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    selectedNum,
    onBatchDel,
    onSearch,
    resetForm,
    openDialog,
    handleDelete,
    onSelectionCancel,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
